package spaceinvaders;

import java.awt.event.KeyEvent;
import java.io.File;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.ImageIcon;


public class Player extends Sprite implements Common{

	private final int START_Y = 474; 
	private final int START_X = 404;

	private final String player = "spacepix/player.png";
	private int playerWidth, damageDelay;
	private Clip clip;

	public Player() {

		ImageIcon playerImage = new ImageIcon(player);

		this.origImage = playerImage.getImage();
		
		playerWidth = playerImage.getImage().getWidth(null);
		damageDelay=6;

		setImage(playerImage.getImage());
		setX(START_X);
		setY(START_Y);
		try {
			clip = AudioSystem.getClip();
			AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File("sounds/drive.wav"));
			clip.open(inputStream);
		} catch (Exception e1) {
			System.err.println(e1.getMessage());
		}
	}

	public void act() {
		x += dx;
		if (x <= playerWidth/2) {
			x = playerWidth/2;
			clip.stop();
			clip.setMicrosecondPosition(0);
		}
		if (x >= BOARDX - (int)(1.5*playerWidth)) {
			x = BOARDX - (int)(1.5*playerWidth);
			clip.stop();
			clip.setMicrosecondPosition(0);
		}
	}

	public void keyPressed(KeyEvent e) {
		int key = e.getKeyCode();

		if (key == KeyEvent.VK_LEFT) {
			dx = -3;
			if (!clip.isActive() && x>playerWidth) {
				clip.start();
			}
		}

		if (key == KeyEvent.VK_RIGHT && x < BOARDX - 2*playerWidth) {
			dx = 3;
			if (!clip.isActive()) {
				clip.start();
			}
		}

	}

	public void keyReleased(KeyEvent e) {
		int key = e.getKeyCode();

		if (key == KeyEvent.VK_LEFT)
		{
			dx = 0;
			clip.stop();
			clip.setMicrosecondPosition(0);
		}

		if (key == KeyEvent.VK_RIGHT)
		{
			dx = 0;
			clip.stop();
			clip.setMicrosecondPosition(0);
		}
	}
	
	public void stopSound() {
		clip.stop();
	}
	
	public void resetDamageDelay() {
		damageDelay=0;
	}
	
	public void incrementDamageDelay() {
		damageDelay++;
	}
	
	public int getDamageDelay() {
		return damageDelay;
	}
}